package com.lazyben.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lazyben.model.Message;
import com.lazyben.util.MessageUtils;
import com.lazyben.util.SpringUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class PushServer extends Thread {
    @Value("${server.netty.port}")
    private int port;

//    @Autowired
//    private PushServerHandler pushServerHandler;

    @Override
    public void run() {
        startServer();
    }

    public static void send(Message message, ChannelHandlerContext ctx) {
        if (ctx != null && message != null) {
            try {
                ctx.writeAndFlush(MessageUtils.messageWrapper(message));
//                ctx.writeAndFlush(Unpooled.copiedBuffer(new ObjectMapper().writeValueAsString(message), StandardCharsets.UTF_8));
                log.info("send message to client, clientId={}, message={}, channelId={}", message.getClientId(), message, ctx.channel().id());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                           .channel(NioServerSocketChannel.class)
                           .childHandler(new ChannelInitializer<SocketChannel>() {
                               @Override
                               protected void initChannel(SocketChannel socketChannel) throws Exception {
                                   socketChannel.pipeline()
                                                .addLast(new DelimiterBasedFrameDecoder(1024 * 1024, Unpooled.copiedBuffer("\r\n".getBytes())))
                                                .addLast(SpringUtils.getBean(PushServerHandler.class));
                               }
                           })
                           .option(ChannelOption.SO_BACKLOG, 128)
                           .childOption(ChannelOption.SO_KEEPALIVE, true);
            channelFuture = serverBootstrap.bind(port).sync();
            log.info("TCP服务端启动成功 Port：{}", port);
        } catch (Exception e) {
            log.info("TCP服务端启动异常 Port：{}", port);
            throw new RuntimeException(e);
        } finally {
            if (channelFuture != null) {
                try {
                    channelFuture.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    log.error("channel关闭异常：", e);
                }
            }
            //线程组资源回收
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
